package com.yuzhi.common.jackson;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yuzhi.common.core.service.OssService;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片地址回显序列化器
 *
 * @author: Mario
 */
public class ImgUrlSerializer extends JsonSerializer<String>  {
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (ObjectUtil.isNull(value) || StringUtils.isBlank(String.valueOf(value))) {
            gen.writeObject(value.toString().trim());
            return;
        }
        // 通过数据图片id获取图片地址
        gen.writeObject(value.toString().trim());
        gen.writeFieldName(gen.getOutputContext().getCurrentName() + "Desc");
        OssService ossService = SpringUtil.getBean(OssService.class);


            // 将逗号分隔的字符串转换为列表
        List<String> valueList = Arrays.asList(value.split(","));

        List urlStr = valueList.stream()
                    .map(ossService::selectUrlById)
                    .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(urlStr) ){
            gen.writeObject(urlStr);
        }
    }
}
